package com.ilikesoup.instant.monitor.sample;

import com.ilikesoup.instant.monitor.core.ChangeEventTrigger;
import com.ilikesoup.instant.monitor.core.Invocation;
import com.ilikesoup.instant.monitor.core.MonitorBeanWrapper;

import java.beans.PropertyChangeSupport;

public class ChangeEventTriggerWrapper implements ChangeEventTrigger {

    private ChangeEventTrigger changeEventTrigger;

    private MonitorBeanWrapper argsBeanMonitorWrapper;

    private MonitorBeanWrapper retValBeanMonitorWrapper;

    public ChangeEventTriggerWrapper() {
    }

    public ChangeEventTriggerWrapper(ChangeEventTrigger changeEventTrigger) {
        this.changeEventTrigger = changeEventTrigger;
    }

    @Override
    public Object copyOldValue(Invocation invocation) {
        Object oldValue = null;
        if(changeEventTrigger != null) {
            oldValue = changeEventTrigger.copyOldValue(invocation);
        }
        if(argsBeanMonitorWrapper != null) {
            Object[] args = invocation.getArgs();
            for (int i = 0; i < args.length; i++) {
                args[i] = argsBeanMonitorWrapper.wrap(args[i]);
            }
        }
        return oldValue;
    }

    @Override
    public void fireChange(Invocation invocation, Object oldValue, PropertyChangeSupport propertyChangeSupport) {
        if(changeEventTrigger != null) {
            changeEventTrigger.fireChange(invocation, oldValue, propertyChangeSupport);
        }
        if(retValBeanMonitorWrapper != null) {
            invocation.setRetVal(retValBeanMonitorWrapper.wrap(invocation.getRetVal()));
        }
    }

    public ChangeEventTriggerWrapper monitorArgs(MonitorBeanWrapper beanMonitorWrapper) {
        this.argsBeanMonitorWrapper = beanMonitorWrapper;
        return this;
    }

    public ChangeEventTriggerWrapper monitorRetVal(MonitorBeanWrapper beanMonitorWrapper) {
        this.retValBeanMonitorWrapper = beanMonitorWrapper;
        return this;
    }

}
